import { createRouter, createWebHistory } from "vue-router";
import { Session } from "@/utils/storage";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
// import pinia from "@/stores/index";

const pages = import.meta.glob("../views/**/page.js", {
  eager: true,
  import: "default", // 配置拿到默认导出的数据
});
const component = import.meta.glob("../views/**/index.vue", {
  eager: true,
  import: "default", // 配置拿到默认导出的数据
});

interface Meta {
  title: string;
  menuOrder: number;
  showFullScreen?: boolean;
}

const children: Array<{
  path: string;
  name: string;
  component: any;
  meta: Meta;
}> = [];
Object.entries(pages).forEach(([path, meta]) => {
  const commPath = path.replace("page.js", "index.vue");
  path = path.replace("../views", "").replace("/page.js", "") || "/";
  const name = path.split("/").filter(Boolean).join("-") || "index";
  if (!meta.showFullScreen) {
    children.push({
      path,
      name,
      component: component[commPath],
      meta,
    });
  }
});

const routes = [
  {
    path: "/",
    name: "Layout",
    redirect: "/Home",
    children: children,
    component: () => import("../layout/index.vue"),
  },
  {
    path: "/login",
    component: () => import("../views/Login/index.vue"),
  },
  {
    path:'/dataScreen',
    component: () => import("../views/DataScreen/index.vue"),
  }
];
console.log(routes);

const router = createRouter({
  history: createWebHistory("127.0.0.1:3000"),
  routes,
});

const whiteList = ["/Login"] as any;
// 路由加载前
router.beforeEach(async (to, from, next) => {
  console.log(to);
  console.log(from);
  NProgress.configure({ showSpinner: false });
  if (to.meta.title) NProgress.start();
  const token = Session.get("token");
  if (token) {
    if (to.path == "/Login") {
      next("/Home");
      NProgress.done();
    } else {
      next();
      NProgress.done();
    }
  } else {
    if (whiteList.includes(to.path)) {
      next();
      NProgress.done();
    } else {
      next("/Login");
      NProgress.done();
    }
  }
});

// 路由加载后
router.afterEach(() => {
  NProgress.done();
});

export default router;
